package cn.xing.managementSystem.controller;

import cn.xing.managementSystem.bean.ResponseContent;
import cn.xing.managementSystem.utils.Preconditions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.controller
 * @class ExceptionController
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/25 下午10:51
 * @description
 */
@RestControllerAdvice
public class ExceptionController {
    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public ResponseContent<Object> globalException(HttpServletRequest request, Throwable ex) {
        return ResponseContent.buildFail(getStatus(request).value(), ex.getMessage(), buildDetailErrorMessage(ex));
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }


    public String buildDetailErrorMessage(Throwable ex){
        if (Preconditions.isNotBlank(ex)) {
            StringBuilder sbErrorMessage = new StringBuilder();
            StackTraceElement[] var5 = ex.getStackTrace();
            int var6 = var5.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                StackTraceElement ste = var5[var7];
                sbErrorMessage.append(ste.toString()).append("\n");
            }

            return sbErrorMessage.toString();
        } else {
            return null;
        }
    }

}